var express = require("express");
var router = express.Router();

//引入连接数据库模块
const conn = require("../conn");

//连接数据
conn.connect(() => {});
var jsonWrite = function(res, ret) {
    if (typeof ret === "undefined") {
        res.json({
            code: "1",
            msg: "操作失败",
        });
    } else {
        res.json(ret);
    }
};

//添加订单
router.post("/insertOrder", function(req, res) {
    const sqlStr =
        "insert into orders(product,userId,totalPrice,creatTime) values (?,?,?,?)";
    var params = req.body;
    conn.query(
        sqlStr, [params.product, params.userId, params.totalPrice, params.creatTime],
        (err, result) => {
            if (err) {
                throw err;
            }
            if (result) {
                jsonWrite(res, result);
            }
        }
    );
});
//查询订单
router.post("/selOrders", function(req, res) {
    let { userId } = req.body;
    const sqlStr = `select userId,SUM(totalPrice) totalPrices,DATE_FORMAT(creatTime,'%Y-%m') m from orders where userId='${userId}' GROUP BY m`;
    conn.query(sqlStr, (err, result) => {
        if (err) {
            throw err;
        }
        if (result) {
            jsonWrite(res, result);
        }
    });
});

module.exports = router;